//
//  CZStatusPictureView.swift
//  WeiBo
//
//  Created by Apple on 16/9/6.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  每项之间的间距
private let itemMargin: CGFloat = 5
//  每项的宽度
private let itemWidth = CGFloat(Int(ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3)

//  重用标记
private let CZStatusPictureViewCellIdentifier = "CZStatusPictureViewCellIdentifier"
//  微博配图视图
class CZStatusPictureView: UICollectionView {
    
    //  配图数据源
    var picUrls: [CZStatusPictureInfo]? {
        didSet {
            //  通过个数计算配图大小
            let size = calcSize(count: picUrls?.count ?? 0)
            
            
            
            //  更新当前视图约束
            snp_updateConstraints { (make) in
                make.size.equalTo(size)
            }
            
            
            //  显示多个配图个数
            messageLabel.text = "\(picUrls?.count ?? 0)"
            //  设置数据重新加载数据
            reloadData()
        }
    }
    
    // MARK:    --懒加载
    private lazy var messageLabel: UILabel = UILabel(fontSize: 20, textColor: UIColor.brown)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        //  设置大小
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    private func setupUI() {
        
        //  添加控件
        addSubview(messageLabel)
        messageLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        //  注册cell
        register(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: CZStatusPictureViewCellIdentifier)
        
        //  设置数据源代理
        dataSource = self
        
        //  设置代理
        delegate = self
        
        
        
    }
    
    //  根据配图数量计算大小
    private func calcSize(count: Int) -> CGSize {
        
        
        //  计算列数
        let cols = count > 3 ? 3 : count
        //  计算行数
        let rows = (count - 1) / 3 + 1
        
        //  计算宽度
        let currentWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        //  计算高度
        let currentHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        return CGSize(width: currentWidth, height: currentHeight)
    
    }
 

}

extension CZStatusPictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CZStatusPictureViewCellIdentifier, for: indexPath) as! CZStatusPictureViewCell
        //  绑定配图信息
        cell.picUrl = picUrls![indexPath.item].thumbnail_pic
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
//        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
//        
//        browser.sourceImagesContainerView = 原图的父控件;
//        
//        browser.imageCount = 原图的数量;
//        
//        browser.currentImageIndex = 当前需要展示图片的index;
//        
//        browser.delegate = 代理;
//        
//        [browser show]; // 展示图
        
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = picUrls!.count
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
//        NSString *urlStr = [[self.modelsArray[index] thumbnail_pic] stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
//        return [NSURL URLWithString:urlStr];
        
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        
        return URL(string: urlStr)
        
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        let indexPath = IndexPath(item: index, section: 0)
        let cell = self.cellForItem(at: indexPath) as! CZStatusPictureViewCell
        return cell.imageView.image
    }

}

//  自定义微博配图cell
class CZStatusPictureViewCell: UICollectionViewCell {
    //  显示配图
    lazy var imageView: UIImageView = {
        let view = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  保证图片比例不变填充
        view.contentMode = .scaleAspectFill
        //  多余图片剪切掉
        view.clipsToBounds = true
        return view
    }()
    var picUrl: String? {
        didSet {
            
            guard let url = picUrl else {
                return
            }
            //  设置url显示
            imageView.sd_setImage(with: URL(string: url), placeholderImage: UIImage(named: "timeline_image_placeholder"))
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //  添加控件设置约束
    private func setupUI() {
        //  添加控件
        contentView.addSubview(imageView)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
    }
    
}












